import { Form, Row, Col, Input, Select, Button } from "antd";
import React from "react";
import { useState } from "react";
const AddSkuForm = ({ propertyList = [], columns, dataSource = [], setDataSource = Function }) => {
    const [count, setCount] = useState(0);
    const [form] = Form.useForm();


    // Select or Input
    const Element = (dataIndex) => {

        let index = propertyList.findIndex(item => item.propertyName === dataIndex);
        if (index > -1) {
            let list = JSON.parse(propertyList[index].propertyValue);
            return <Select
                options={list.map(item => ({
                    label: item,
                    value: item
                }))}></Select>
        }
        return <Input />
    }


    // 点击添加按钮的事件
    const onFinish = (values) => {
        console.log("表单数据：", values, "原始数据：", dataSource)
        let newData = [...dataSource, {
            key: count,
            ...values
        }]
        setDataSource(newData)
        setCount(count + 1)
        form.resetFields()
    }



    return (
        <div className="table">
            <Form
                className="table-body"
                form={form}
                onFinish={onFinish}
            >
                <Row className="row" gutter={24}>
                    {
                        columns.map((item, i) => {
                            return <Col className="col" span={4} key={i}>
                                {item.title}
                            </Col>
                        })
                    }

                </Row>
                <Row className="row" gutter={24}>
                    {
                        columns.map((item, i) => {
                            if (i === (columns.length - 1)) {
                                return <Col className="col" span={4} key={i}>
                                    <Form.Item>
                                        <Button htmlType="sumbit">添加</Button>
                                    </Form.Item>
                                </Col>
                            }
                            return <Col className="col" span={4} key={i}>
                                <Form.Item
                                    rules={[{
                                        required: true
                                    }]}
                                    label={item.title} name={item.dataIndex}>
                                    {
                                        Element(item.dataIndex)
                                    }
                                </Form.Item>
                            </Col>
                        })
                    }

                </Row>
            </Form>
        </div>
    )
}
export default AddSkuForm;